<?php

// TODO: i18n (Ticket #1133)

function GoogleMap_Header($target) {
	global $configVal, $pluginURL;
	requireComponent('Textcube.Function.Setting');
	$config = Setting::fetchConfigVal($configVal);
	if (!is_null($config) && isset($config['apiKey'])) {
		$api_key = $config['apiKey'];
		$target .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"$pluginURL/common.css\" />\n";
		$target .= "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi?key=$api_key\"></script>\n";
		$target .= "<script type=\"text/javascript\">
		//<![CDATA[
		google.load(\"maps\", \"2\");
		STD.addUnloadEventListener(function(){GUnload();});
		//]]>
		</script>\n";
		$target .= "<script type=\"text/javascript\" src=\"$pluginURL/scripts/common.js\"></script>\n";
	}
	return $target;
}

function GoogleMap_AdminHeader($target) {
	global $suri, $pluginURL, $blogURL, $serviceURL, $configVal, $blog, $service;
	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
	if ($suri['directive'] == '/owner/entry/post' || $suri['directive'] == '/owner/entry/edit') {
		requireComponent('Textcube.Function.Setting');
		$config = Setting::fetchConfigVal($configVal);
		$api_key = $config['apiKey']; // should exist here
		$target .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"$pluginURL/common.css\" />\n";
		$target .= "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi?key=$api_key\"></script>\n";
		$target .= "<script type=\"text/javascript\">
		//<![CDATA[
		var pluginURL = '$pluginURL';
		var blogURL = '$blogURL';
		var i18n = '".$blog['blogLanguage']."';
		google.load(\"maps\", \"2\");
		//]]>
		</script>";
		$target .= "<script type=\"text/javascript\" src=\"$pluginURL/scripts/common.js\"></script>\n";
		$target .= "<script type=\"text/javascript\" src=\"$pluginURL/scripts/editor.js\"></script>\n";
	}
	return $target;
}

function GoogleMap_AddToolbox($target) {
	global $pluginURL, $blog, $service;
	if (!isset($blog['blogLanguage'])) $blog['blogLanguage'] = $service['language'];
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$imgdesc ='插入 Google 地圖';
		break;
		case "zh-CN":
			$imgdesc ='插入 Google 地图';
		break;
		default:
			$imgdesc = '구글맵 추가하기';
	}
	if(!empty($languageFile)) { include ($languageFile); }	
	$target .= "<img src=\"$pluginURL/images/gmap_toolbar.gif\" border=\"0\" alt=\"$imgdesc\" onclick=\"GMapTool_Insert();\" style=\"cursor:pointer\" />\n";
	return $target;
}

function GoogleMap_View($target, $mother) {
	global $configVal, $pluginURL, $blog, $service;
	requireComponent('Textcube.Function.Setting');
	requireComponent('Textcube.Function.Misc');
	$config = Setting::fetchConfigVal($configVal);
	if (!isset($blog['blogLanguage'])) $blog['blogLanguage'] = $service['language'];
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$err ='此瀏覽器不支援 Google 地圖。';
		break;
		case "zh-CN":
			$err ='此浏览器不支持 Google 地图。';
		break;
		default:
			$err = '이 웹브라우저는 구글맵과 호환되지 않습니다.';
	}
	$matches = array();
	$offset = 0;
	while (preg_match('/\[##_GoogleMap\|(([^|]+)\|)?_##\]/', $target, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
		// SUGGUEST: [##_GoogleMap|{JSON_REPRESENTATION_OF_PARAMETERS_WITHOUT_NEWLINES}|_##]
		$id = 'GMapContainer'.$mother.rand();
		ob_start();
?>
		<div id="<?php echo $id;?>" style="border: 1px solid #666;"></div>
		<script type="text/javascript">
		//<![CDATA[
		var c = document.getElementById('<?php echo $id;?>');
		if (GBrowserIsCompatible()) {
			var map = GMap_CreateMap(c, <?php echo $matches[2][0];?>);
		} else {
			c.innerHTML = '<p style="text-align:center; color:#c99;"><?php echo $err;?></p>';
		}
		//]]>
		</script>
<?php
		$output = ob_get_contents();
		ob_end_clean();
		$target = substr_replace($target, $output, $matches[0][1], strlen($matches[0][0]));
		$offset += $matches[0][1] + strlen($output);
	}
	return $target;
}

function GoogleMap_LocationLogView($target) {
	global $blogid, $blog, $blogURL, $pluginURL, $configVal, $service, $database, $service;
	requireComponent('Textcube.Function.Misc');
	$config = Setting::fetchConfigVal($configVal);
	if (!isset($blog['blogLanguage'])) $blog['blogLanguage'] = $service['language'];
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$err ='此瀏覽器不支援 Google 地圖。';
		break;
		case "zh-CN":
			$err ='此浏览器不支持 Google 地图。';
		break;
		default:
			$err = '이 웹브라우저는 구글맵과 호환되지 않습니다.';
	}
	$locatives = getLocatives($blogid);
	$width = Misc::getContentWidth();
	$height = intval($width * 1.2);
	$default_type = isset($config['locative_maptype']) ? $config['locative_maptype'] : 'G_HYBRID_MAP';
	$id = 'LocationMap';
	$lat = $config['latitude'];
	$lng = $config['longitude'];
	$zoom = 10;
	ob_start();
?>
	<div style="text-align:center;">
		<div id="<?php echo $id;?>" style="margin:0 auto;"></div>
	</div>
	<script type="text/javascript">
	//<![CDATA[
	//console.log('a');
	var process_count = 0;
	var polling_interval = 100; // ms
	var query_interval = 500; // ms
	var query_interval_handle = null;
	var progress = null;
	var boundary = null;
	var locationMap = null;
	function adjustToBoundary() {
		var z = locationMap.getBoundsZoomLevel(boundary);
		if (z > 8)
			z--;
		if (z > 12)
			z = 12;
		locationMap.setZoom(z);
		locationMap.setCenter(boundary.getCenter());
	}
	function locationFetch(tofind) {
		if (tofind.length == 0) {
			window.clearInterval(query_interval_handle);
			return;
		}
		GMap_addLocationMark.apply(this, tofind.pop());
	}
	function locationFetchPoller(target_count) {
		var e = document.getElementById('gmap-progress');
		var p = document.getElementById('gmap-progress-meter');
		if (process_count != target_count) {
			progress.setProgress(process_count / target_count);
			window.setTimeout('locationFetchPoller('+target_count+');', polling_interval);
			return;
		}
		progress.setProgress(1.0);
		window.setTimeout(function() {locationMap.removeControl(progress);}, 200); // eyecandy
		adjustToBoundary();
	}
	STD.addLoadEventListener(function() {
		var c = document.getElementById('<?php echo $id;?>');
		c.style.width = "<?php echo $width;?>px"
		c.style.height = "<?php echo $height;?>px";
		if (GBrowserIsCompatible()) {
			locationMap = new GMap2(c);
			locationMap.addMapType(G_PHYSICAL_MAP);
			locationMap.setMapType(<?php echo $default_type;?>);
			locationMap.addControl(new GHierarchicalMapTypeControl());
			locationMap.addControl(new GLargeMapControl());
			locationMap.addControl(new GScaleControl());
			locationMap.enableContinuousZoom();
			locationMap.setCenter(new GLatLng(<?php echo $lat;?>, <?php echo $lng;?>), <?php echo $zoom;?>);
			progress = new GProgressControl();
			locationMap.addControl(progress);
			boundary = new GLatLngBounds(locationMap.getCenter());
			var locations = new Array();
			var tofind = new Array();
<?php
	$count = 0;
	$countRemoteQuery = 0;
	foreach ($locatives as $locative) {
		//if ($count == 10) break; // for testing purpose
		$locative['link'] = "$blogURL/" . ($blog['useSloganOnPost'] ? 'entry/' . URL::encode($locative['slogan'],$service['useEncodedURL']) : $locative['id']);
		$row = POD::queryRow("SELECT * FROM {$database['prefix']}GMapLocations WHERE blogid = ".getBlogId()." AND original_address = '".POD::escapeString($locative['location'])."'");
		$found = false;
		if ($row == null || empty($row)) {
			$found = false;
		} else {
			$lat = $row['latitude'];
			$lng = $row['longitude'];
			$found = true;
		}
		if ($found) // found, just output
			echo "\t\t\tGMap_addLocationMarkDirect(locationMap, {address:GMap_normalizeAddress('{$locative['location']}'), path:'{$locative['location']}', original_path:'{$locative['location']}'}, '".str_replace("'", "\\'", $locative['title'])."', encodeURI('".str_replace("'", "\\'", $locative['link'])."'), new GLatLng($lat, $lng), boundary, locations, false);\n";
		else // try to find in the client
			echo "\t\t\ttofind.push([locationMap, '{$locative['location']}', '".str_replace("'", "\\'", $locative['title'])."', encodeURI('".str_replace("'", "\\'", $locative['link'])."'), boundary, locations]);\n";
		$count++;
	}
?>
			progress.setLabel('Loading locations...');
			query_interval_handle = window.setInterval(function() {locationFetch(tofind);}, query_interval);
			window.setTimeout(function() {locationFetchPoller(<?php echo $count;?>);}, polling_interval);
		} else {
			c.innerHTML = '<p style="text-align:center; color:#c99;"><?php echo $err;?></p>';
		}
	});
	//]]>
	</script>
<?php
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

function GoogleMap_ConfigHandler($data) {
	global $blog, $service;
	if (!isset($blog['blogLanguage'])) $blog['blogLanguage'] = $service['language'];
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$err ='經緯度設定錯誤。';
		break;
		case "zh-CN":
			$err ='经纬度设定错误。';
		break;
		default:
			$err = '위도 또는 경도의 값이 올바르지 않습니다.';
	}
	requireComponent('Textcube.Function.Setting');
	$config = Setting::fetchConfigVal($data);
	if (!is_numeric($config['latitude']) || !is_numeric($config['longitude']) ||
		$config['latitude'] < -90 || $config['latitude'] > 90 || $config['longitude'] < -180 || $config['longitude'] > 180)
		return $err;
	return true;
}

function GoogleMap_Cache() {
	global $database;
	$IV = array(
		'POST' => array(
			'original_path' => array('string', 'default'=>''),
			'path' => array('string', 'default'=>''),
			'lat' => array('number', 'default'=>null),
			'lng' => array('number', 'default'=>null)
		)
	);
	Validator::validate($IV);
	if (empty($_POST['path']) || empty($_POST['original_path'])) {
		echo 'error: empty path';
		return;
	}
	$original_path_e = POD::escapeString($_POST['original_path']);
	$path_e = POD::escapeString($_POST['path']);
	$row = POD::queryRow("SELECT * FROM {$database['prefix']}GMapLocations WHERE blogid = ".getBlogId()." AND original_address = '$original_path_e'");
	if ($row == null || empty($row)) {
		if (POD::execute("INSERT INTO {$database['prefix']}GMapLocations VALUES (".getBlogId().", '$original_path_e', '$path_e', {$_POST['lng']}, {$_POST['lat']}, ".$_SERVER['REQUEST_TIME'].")"))
			echo 'ok';
		else
			echo 'error: cache failed';
	} else {
		echo 'duplicate';
	}
}

function GoogleMapUI_Insert() {
	global $configVal, $pluginURL, $blog, $service;
	requireComponent('Textcube.Function.Misc');
	$config = Setting::fetchConfigVal($configVal);
	if (!isset($blog['blogLanguage'])) $blog['blogLanguage'] = $service['language'];
	$gtext = array();
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$gtext[0] ='插入 Google 地圖';
			$gtext[1] = '加入記錄器';
			$gtext[2] = '插入文章';
			$gtext[3] = '導引搜尋';
			$gtext[4] = '位置搜尋';
			$gtext[5] = '搜尋';
			$gtext[6] = '基本設定';
			$gtext[7] = '寬度';
			$gtext[8] = '高度';
			$gtext[9] = '套用';
		break;
		case "zh-CN":
			$gtext[0] ='插入 Google 地图';
			$gtext[1] = '加入记录器';
			$gtext[2] = '插入文章';
			$gtext[3] = '导引搜寻';
			$gtext[4] = '位置搜寻';
			$gtext[5] = '搜寻';
			$gtext[6] = '基本设定';
			$gtext[7] = '宽度';
			$gtext[8] = '高度';
			$gtext[9] = '套用';
		break;
		default:
			$gtext[0] = '구글맵 삽입하기';
			$gtext[1] = '마커 표시 모드';
			$gtext[2] = '본문에 삽입하기';
			$gtext[3] = '지도 검색';
			$gtext[4] = '위치 검색';
			$gtext[5] = '찾기';
			$gtext[6] = '기본 설정';
			$gtext[7] = '가로';
			$gtext[8] = '세로';
			$gtext[9] = '적용';
	}
	$lat = $config['latitude'];
	$lng = $config['longitude'];
	$default_type = 'G_HYBRID_MAP';
	$default_width = min(Misc::getContentWidth(), 500);
	$default_height = 400;
	$zoom = 10;
	_GMap_printHeaderForUI($gtext[0], $config['apiKey']);
?>
	<div id="controls">
		<button id="toggleMarkerAddingMode"><?php echo $gtext[1];?></button>
		<button id="doInsert"><?php echo $gtext[2];?></button>
	</div>
	<div style="text-align:center;">
		<div id="GoogleMapPreview" style="width:<?php echo $default_width;?>px; height:<?php echo $default_height;?>px; margin:0 auto;"></div>
	</div>
	<script type="text/javascript">
	//<![CDATA[
	function initializeMap() {
		map = new GMap2($('#GoogleMapPreview')[0]);
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(<?php echo $default_type;?>);
		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.setCenter(new GLatLng(<?php echo $lat;?>, <?php echo $lng;?>), <?php echo $zoom;?>);
	}
	//]]>
	</script>
	<h2><?php echo $gtext[3];?></h2>
	<div class="accordion-elem">
		<p><label><?php echo $gtext[4];?> : <input type="text" class="editControl" id="inputQuery" value="" /></label><button id="queryLocation"><?php echo $gtext[5];?></button></p>
	</div>
	<h2><?php echo $gtext[6];?></h2>
	<div class="accordion-elem">
		<p><label><?php echo $gtext[7];?>(px) : <input type="text" class="editControl" id="inputWidth" value="<?php echo $default_width;?>" /></label></p>
		<p><label><?php echo $gtext[8];?>(px) : <input type="text" class="editControl" id="inputHeight" value="<?php echo $default_height;?>" /></label></p>
		<p><button id="applyBasicSettings"><?php echo $gtext[9];?></button></p>
	</div>
<?php
	// TODO: 주소 추출 UI
	// - TODO: 포스트 내용 텍스트 얻어오기 및 주소 정보 추출
	_GMap_printFooterForUI();
}

function _GMap_printHeaderForUI($title, $api_key) {
	global $pluginURL, $blogURL, $service, $adminSkinSetting, $blog;
	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Google Map Plugin: <?php echo $title;?></title>
	<link rel="stylesheet" type="text/css" href="<?php echo $pluginURL;?>/insert.css" />
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/jquery-1.2.6.min.js"></script>
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/jquery-ui-1.6rc2.js"></script>
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/jquery-mousewheel.min.js"></script>
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/jquery-json.js"></script>
	<script type="text/javascript" src="http://www.google.com/jsapi?key=<?php echo $api_key;?>"></script>
	<script type="text/javascript">
	//<![CDATA[
	var pluginURL = '<?php echo $pluginURL;?>';
	var blogURL = '<?php echo $blogURL;?>';
	var i18n = '<?php echo $blog['blogLanguage'];?>';
	google.load("maps", "2");
	//]]>
	</script>
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/common.js"></script>	
	<script type="text/javascript" src="<?php echo $pluginURL;?>/scripts/insert.js"></script>
</head>
<body>
<div id="all-wrap">
	<h1><?php echo $title;?></h1>
	<div id="layout-body">
<?php
}

function _GMap_printFooterForUI() {
?>
	</div>
</div>
<script type="text/javascript">
//<![CDATA[	
$(window).unload(GUnload);
//]]>
</script>
</body>
</html>
<?php
}

function _GMap_normalizeAddress($address) {
	return trim(implode(' ', explode('/', $address)));
}
/* vim: set noet ts=4 sts=4 sw=4: */
?>